%%%%%%%%%%%%
% Cross-sectional smoothing of the moment estimates
% to reduce estimation errors
% Liuren Wu, liurenwu@gmail.com
%%%%%%%%%%%%
function yh= FunMomentCSSmoothing(y,d1,mat,bdsd,bdsm)
yh=y;
ix=isfinite(y);y=y(ix);
nobs=sum(ix);
sigmax=std(d1);  hx=bdsd*(4/3)^(1/6)*sigmax/nobs^(1/6);
sigmam=std(mat); hm=bdsm*(4/3)^(1/6)*sigmam/nobs^(1/6);
yhh=y;
d1i=d1(ix); mi=mat(ix);

x=[ones(nobs,1),d1i,mi];
for i=1:nobs
    dx=abs(d1i(i)-d1i); xt=dx/hx;
    dx=abs(mi(i)-mi); mt=dx/hm;
    w=exp(-xt.^2/2-mt.^2/2);
    yhh(i)=sum(w.*y)/sum(w);
end
yh(ix)=yhh;
